from django.http import HttpResponse, HttpResponseRedirect
from django.template import RequestContext, loader
from django.contrib.auth import authenticate, login, logout
from django.shortcuts import render, redirect
from django.views.decorators.csrf import csrf_exempt
from cashgirls import cashGUtil
from django.utils import translation
from datetime import datetime, timedelta
from cashgirls import views as viewsRoot
from models import MerchantUser, ShopperUser, AbstractUser, AbstractProfile, Request, STATUS, USER_TYPE, RETURN_STATUS, Purchase, BankAccount, MerchantProfile, Payment, ShopperProfile, BANK_ACCOUNT_TYPE, PAYMENT_STATUS, LocalizedModel, ACCEPTED_LOCALE
from django.contrib import messages
from django.conf import settings
from Crypto.Cipher import XOR
import stripe
import json
import re
from django.db import connection

SECRET_KEY = "cashGSecretkeySK"
CONFIRMATION_LINK_INVALID_CHARS = "[/?$=+]"


def validate(request):
    if 'username' not in request.POST:
        return redirect('index')
    username = request.POST['username']
    password = request.POST['password']
    user = authenticate(username=username, password=password)
    if user is not None:
        if user.is_superuser:
            login(request, user)
            return redirect('/admins/console/')
        else:
            abstractUser = None
            try:
                abstractUser = MerchantUser.objects.get(user=user)
            except MerchantUser.DoesNotExist:
                abstractUser = ShopperUser.objects.get(user=user)
            if abstractUser.confirmed:
                login(request, user)
                request.session['django_language'] = ACCEPTED_LOCALE.get_lang_code(abstractUser.lang).lower()
            else:
                messages.add_message(request, messages.ERROR, 'Password or username incorrect.')
    else:
        messages.add_message(request, messages.ERROR, 'Password or username incorrect.')
    return redirect('index')

def list_marchants_api(request):
    users = MerchantUser.objects.all()
    user_out = []
    for user in users:
        user_response = {}
        active_profile = user.getActiveProfile()
        if active_profile:
            try:
                user_response["username"] = user.username
                user_response["id"] = user.id
                user_response["updateDate"] = int(user.update_date.strftime('%s'))
                image_filter = active_profile.images.get(id=user.profile_image)
                user_response["pofileImg"] = settings.S3_URL  + str(image_filter.thumbnail)
            except Exception:
                user_response["pofileImg"] = settings.S3_URL + "documents/unknown/unknown.jpg"
            user_out.append(user_response)
    return HttpResponse(json.dumps(user_out), content_type="application/json")

def merchant_profile_get_api(request, user_id):
    res = {}
    try:
        merchant = MerchantUser.objects.get(id=user_id)
        res["username"] = merchant.username
        res["age"] = merchant.age
        res["description"] = merchant.getActiveProfile().profile
        res["defaultImage"] = merchant.profile_image
        res["updateDate"] = int(merchant.update_date.strftime('%s'))
        image_list = []
        for image in merchant.getActiveProfile().images.all():
            image_res = {}
            image_res["image"] = settings.MEDIA_URL + image.image.name
            image_res["thumbnail"] = settings.MEDIA_URL + image.thumbnail.name
            image_res["id"] = image.id
            image_list.append(image_res)
        res["pics"] = image_list
    except MerchantUser.DoesNotExist:
        res["status"] = RETURN_STATUS.choices[RETURN_STATUS.OBJECT_NOT_FOUND]
    return HttpResponse(json.dumps(res), content_type="application/json")


def create_request(request, sender_user_id, receiver_user_id):
    if request.user.is_authenticated():
        enableSend = True
        sender_user = ShopperUser.objects.get(id=sender_user_id)
        receiver_user = MerchantUser.objects.get(id=receiver_user_id)
        requests = Request.objects.filter(sender=sender_user, receiver=receiver_user, status__in=[STATUS.DELIVERY_PENDING, STATUS.ON_REVIEW, STATUS.PENDING_ANSWER])
        if viewsRoot.isUserHasPendingRequests(sender_user, receiver_user):
            enableSend = False
            messages.add_message(request, messages.ERROR, 'Pending requeset exists for this merchant')
        else:
            req= Request.objects.create(
            sender = sender_user,
            receiver = receiver_user,
            request_text = request.POST['request_text'])
            req.save()
            messages.add_message(request, messages.SUCCESS, 'Request succesfuly created')
            enableSend = False

        return viewsRoot.display_profile(request, receiver_user.id)
    return redirect('index')


def signUpForm(request):
    template = loader.get_template('main/signUpForm.html')
    context = RequestContext(request, {})
    return HttpResponse(template.render(context))

def shopperSignUpForm(request):
    template = loader.get_template('main/shopperSignUpForm.html')
    context = RequestContext(request, {})
    return HttpResponse(template.render(context))

def logoutted(request):
    logout(request)
    return redirect('index')

def lang_set(request):
    if request.user.is_authenticated():
        lang = request.POST['language']
        user = request.user
        abstractUser = AbstractUser.objects.get(user=user)
        abstractUser.lang = ACCEPTED_LOCALE.get_constant(lang.upper())
        abstractUser.save()
    return HttpResponseRedirect('/') 


def my_account(request):
    if request.user.is_authenticated():
        user = request.user
        try:
            merchantUser = MerchantUser.objects.get(user=user)
        except MerchantUser.DoesNotExist:
            merchantUser = None
        return render(request, 'main/myAccount.html', {'user': merchantUser or user,})
    return render(request, 'main/index.html')

def my_profile(request):
    if request.user.is_authenticated():
        user = request.user
        usrObj = _getAbstractUser(user.id)
        profile = usrObj.getPendingProfile()
        img_active_profile = []
        if usrObj.getActiveProfile():
            images = usrObj.getActiveProfile().images.all()
            for img in images:
                img_active_profile.append(img.image)
        if not profile:
            profile = usrObj.getActiveProfile()
        locale_profile = _get_profile_for_usr(profile)
        return render(request, 'main/myProfile.html', {'user': usrObj, "profile" : profile, "active_images_path": img_active_profile, "locales": locale_profile})
    return redirect('index')

# Get all the loc_profiles for all the languages
def _get_profile_for_usr(profile):
    locale_profile = {}
    for choice in ACCEPTED_LOCALE.choices:
        tmp_prof = None
        if profile:
            tmp_prof = profile.getLocProfile(choice)                
        locale_profile[(choice, ACCEPTED_LOCALE.choices[choice])] = tmp_prof
    return locale_profile

def my_bank(request, user_id):
    if request.user.is_authenticated():
        user = request.user
        if not user.is_superuser:
            if user.id != int(user_id):
                messages.add_message(request, messages.ERROR, 'Access not allowed')
                return redirect('index')
        merchantUser = MerchantUser.objects.get(id=user_id)
        return render(request, 'main/myBank.html', {'bank': merchantUser.bank, "account_type" : BANK_ACCOUNT_TYPE, "editable": not user.is_superuser})
    return redirect('index')

def payment_request_form(request):
    if request.user.is_authenticated():
        user = request.user
        merchantUser = MerchantUser.objects.get(user=user)
        return render(request, 'main/paymentRequest.html', {'user': merchantUser, 'PAYMENT_STATUS': PAYMENT_STATUS,})
    return redirect('index')
   
def payment_cancel(request, payment_id):
    if request.user.is_authenticated():
        payment = Payment.objects.get(id=payment_id)
        if payment.status == PAYMENT_STATUS.CANCELED:
            messages.add_message(request, messages.WARNING, 'This payment was already canceled')
            return redirect("payment_request_form")
        payment.status = PAYMENT_STATUS.CANCELED
        payment.save()
        # give back the points to the merchant
        merchantUser = MerchantUser.objects.get(user=request.user)
        merchantUser.points = int(merchantUser.points) + payment.amount
        merchantUser.save()
        return redirect("payment_request_form")
    return redirect('index')

def payment_submit(request):
    if request.user.is_authenticated():
        user = request.user
        merchantUser = MerchantUser.objects.get(user=user)
        # if the merchant has no bank associated, the payment cannot be processed
        if not merchantUser.bank:
            messages.add_message(request, messages.WARNING, 'Provide bank information for request a payment')
            return redirect("payment_request_form")
        amount = int(request.POST["amount"])
        if amount > int(merchantUser.points):
            messages.add_message(request, messages.WARNING, 'maximum amount for being requested is %s' %(merchantUser.points))
            return redirect("payment_request_form")        
        # create the payment object
        payment = Payment(merchant = merchantUser, amount = amount)
        payment.save()
        # deduct the amount from the merchant's point
        merchantUser.points = int(merchantUser.points) - amount
        merchantUser.save()        
        return redirect("payment_request_form")
    return redirect('index')

def bank_update(request):
    if request.user.is_authenticated():
        user = request.user
        merchantUser = MerchantUser.objects.get(user=user)
        #check if there is a pending payment for this merchant
        for payment in merchantUser.payments.all():
            if payment.status == PAYMENT_STATUS.PENDING:
                messages.add_message(request, messages.SUCCESS, 'There is pending payment, cannot update bank information')
                return my_bank(request, merchantUser.id)
        bank_info = BankAccount()
        if merchantUser.bank:
            bank_info = merchantUser.bank
            bank_info.bank_name = request.POST["bankName"]
            bank_info.holder_name = request.POST["holderName"]
            bank_info.account_number = request.POST["accountNumber"]
        bank_info.account_type = request.POST["accountType"]
        bank_info.swift = request.POST["swift"]
        bank_info.save()
        merchantUser.bank = bank_info
        merchantUser.save()
        messages.add_message(request, messages.SUCCESS, 'Bank information Saved')
        return my_bank(request, merchantUser.id)
    return redirect('index')

def profile_pendant(request, username):
    if request.user.is_authenticated():
        user = request.user
        merchantUser = MerchantUser.objects.get(user=user)
        profile = merchantUser.getPendingProfile()
        if not profile:
            profile = merchantUser.getActiveProfile()
        return render(request, 'main/myProfile.html', {'user': merchantUser, "profile" : profile,})
    return redirect('index')

def request_approve(request, request_id):
    if request.user.is_authenticated():
        requestObj = Request.objects.get(id = request_id)
        requestObj.status = STATUS.PENDING_ANSWER
        requestObj.save()
        return redirect('/member/requests/view/')
    return redirect('index')

def request_approve_asset(request, request_id):
    if request.user.is_authenticated():
        requestObj = Request.objects.get(id = request_id)
        requestObj.status = STATUS.DELIVERED
        requestObj.expiration_date = None
        requestObj.save()
        # Credit points to the merchant
        merchantUser = requestObj.receiver
        merchantUser.points = int(merchantUser.points) + int(requestObj.price)
        merchantUser.save()
        return redirect('/member/requests/view/')
    return redirect('index')

def request_reject_asset(request, request_id):
    if request.user.is_authenticated():
        requestObj = Request.objects.get(id = request_id)
        requestObj.status = STATUS.DELIVERY_PENDING
        requestObj.expiration_date = datetime.now() + timedelta(days=1)
        requestObj.rejection_comment = request.POST['reject_comment']
        requestObj.save()
        return redirect('/member/requests/view/')
    return redirect('index')

def request_accept(request, request_id):
    if request.user.is_authenticated():
        requestObj = Request.objects.get(id = request_id)
        requestObj.status = STATUS.ACCEPTED
        requestObj.price = request.POST['priceVal']
        requestObj.save()
        return redirect('/member/requests/view/')
    return redirect('index')

def request_reject_admin(request, request_id):
    if request.user.is_authenticated():
        _request_reject(request, request_id, STATUS.REJECTED_BY_ADMIN)
        return redirect('/member/requests/view/')
    return redirect('index')

def request_reject_merchant(request, request_id):
    if request.user.is_authenticated():
        _request_reject(request, request_id)
        return redirect('/member/requests/view/')
    return redirect('index')

def request_send(request, request_id):
    if request.user.is_authenticated():
        requestObj = Request.objects.get(id = request_id)
        if requestObj.linkedPurchase.all():
            purchase = requestObj.linkedPurchase.all()[0]
        else:
            purchase = Purchase()
            purchase.request = requestObj
        if 'datafile' in request.FILES:
            purchase.asset = request.FILES['datafile']
        purchase.expiration_date = datetime.now() + timedelta(days=7)
        purchase.save()
        requestObj.status = STATUS.DELIVERY_ON_REVIEW
        requestObj.rejection_comment = request.POST['reject_comment']
        requestObj.expiration_date = None
        requestObj.save()
        return redirect('/member/shopper/requestFulFill/' + str(requestObj.id) + '/')
    return redirect('index')

def request_buy(request, request_id):
    if request.user.is_authenticated():
        requestObj = Request.objects.get(id = request_id)
        user = request.user
        shopperUser = ShopperUser.objects.get(user=user)
        # discount points from shopper
        if int(shopperUser.points) >= int(requestObj.price):
            shopperUser.points = int(shopperUser.points) - int(requestObj.price)
            shopperUser.save()
            requestObj.status = STATUS.DELIVERY_PENDING
            requestObj.expiration_date = datetime.now() + timedelta(days=2)
            requestObj.save()
        else:
            messages.add_message(request, messages.WARNING, 'Not enough points to buy this asset')

        return redirect('/member/requests/view/')
    return redirect('index')

def points_credit(request):
    if request.user.is_authenticated():
        user = request.user
        shopperUser = ShopperUser.objects.get(user=user)
        point = request.POST["credit_ammount"]
        shopperUser.points = int(shopperUser.points) + int(point)
        shopperUser.save()
    return redirect('index')

def points_buy(request):
    if request.user.is_authenticated():
        
        return render(request, 'main/pointsPurchaseForm.html')
    return redirect('index')

def points_payment(request):
    if request.user.is_authenticated():
        cipher = XOR.new(SECRET_KEY) 
        if "stripeToken" in request.POST:
            enc_points = request.POST["stpnct"]
            if enc_points:
                points = cipher.decrypt(enc_points)
                if not points.isdigit():
                    messages.add_message(request, messages.ERROR, 'Credit card form altered, transaction invalid')
                else:

                    _charge_to_CC(request.POST["stripeToken"], points)
                    user = request.user
                    shopperUser = ShopperUser.objects.get(user=user)
                    shopperUser.points = int(shopperUser.points) + int(points)
                    shopperUser.save()
                    return redirect('index')
        
        if "credit_ammount" in request.POST:
            points = request.POST["credit_ammount"]
            
            if int(points) < settings.MINIMUM_PURCHASE_AMOUNT:
                messages.add_message(request, messages.WARNING, 'Minimum amount of points to purchase is %s' % str(settings.MINIMUM_PURCHASE_AMOUNT))
                points = str(settings.MINIMUM_PURCHASE_AMOUNT)
        else:
            points = "0"
        encoded_pts = cipher.encrypt(points)
        return render(request, 'main/paymentForm.html', {'points': points, 'encoded_pts': encoded_pts, 'publishable_key': settings.SHOP_STRIPE_PUBLISHABLE_KEY, 'is_debug':(settings.DEBUG == True), "price": int(points)*(0.01), "currency":"USD"})
    return redirect('index')

def _charge_to_CC(stripe_token, amount_pts):
    stripe.api_key = settings.SHOP_STRIPE_PRIVATE_KEY

    # Create the charge on Stripe's servers - this will charge the user's card
    try:
        charge = stripe.Charge.create(amount=amount_pts, currency="usd", card=stripe_token, description="payinguser@example.com")
        return True
    except stripe.CardError, e:
        # The card has been declined
        return False
        pass
 
# Puajj, horrible method, there HAS to be a better way to do this!!!   
def _getAbstractUser(user_id):
    abstractUser = None
    try:
        abstractUser = MerchantUser.objects.get(id=user_id)
    except MerchantUser.DoesNotExist:
        abstractUser = ShopperUser.objects.get(id=user_id)
    return abstractUser
    

def request_fulfill(request, request_id):
    if request.user.is_authenticated():
        requestObj = Request.objects.get(id = request_id)
        return render(request, 'main/fulfillRequestForm.html', {'user': request.user, "request" : requestObj,})
    return redirect('index')

def _request_reject(request, request_id, status = STATUS.REJECTED_BY_USER):
        requestObj = Request.objects.get(id = request_id)
        requestObj.status = status
        comment = request.POST['reject_comment']
        if not comment:
            comment = 'No comment provided'
        requestObj.rejection_comment = comment
        requestObj.save()

def profile_approval_view(request):
    if request.user.is_authenticated():
        merchant_request_out = []
        merchantProfiles = MerchantProfile.objects.filter(status=STATUS.ON_REVIEW)
        for prof in merchantProfiles:
            merchant_request_out.append((prof, STATUS.choices[prof.status]))
        shopper_request_out = []
        shopperProfiles = ShopperProfile.objects.filter(status=STATUS.ON_REVIEW)
        for prof in shopperProfiles:
            shopper_request_out.append((prof, STATUS.choices[prof.status]))
        return render(request, 'main/myApprovalRequests.html', {'merchant_profiles': merchant_request_out, 'shopper_profiles': shopper_request_out,})
    return redirect('index')   

def profile_approval_view_by_id(request, profile_id):
    if request.user.is_authenticated() and request.user.is_superuser:
        try:
            profile = MerchantProfile.objects.get(id=profile_id)
            locale_profiles = _get_profile_for_usr(profile)
            return render(request, 'main/profileMerchantDisplay.html', {'profile': profile, 'enableSend': False, "logged_user":request.user, "locales": locale_profiles})
        except MerchantProfile.DoesNotExist:
            profile = ShopperProfile.objects.get(id=profile_id)
            return render(request, 'main/profileShopperDisplay.html', {'profile': profile, 'logged_user':request.user,"locales": _get_profile_for_usr(profile)})
    return redirect('index')   

def _profile_approve(request, profile_id, is_merchant, ProfClass):
        profile = ProfClass.objects.get(id=profile_id)
        if is_merchant:
            user = profile.merchantUser
        else:
            user = profile.shopperUser
        active_profile = user.getActiveProfile()
        if active_profile:
            active_profile.status = STATUS.EXPIRED
            active_profile.save()
        
        profile.status = STATUS.ACCEPTED
        profile.save()

def profile_approval_approve(request, profile_id):
    if request.user.is_authenticated():
        try:
            MerchantProfile.objects.get(id=profile_id)
            _profile_approve(request, profile_id, True, MerchantProfile)
        except MerchantProfile.DoesNotExist:
            _profile_approve(request, profile_id, False, ShopperProfile)
        return redirect('/member/profile/approval/view/')  
    return redirect('index') 

def profile_reject(request, profile_id):
    if request.user.is_authenticated():
        profile = AbstractProfile.objects.get(id=profile_id)
        profile.status = STATUS.REJECTED_BY_ADMIN
        profile.status_comment = request.POST["reject_comment"]
        profile.save()
        return redirect('/member/profile/approval/view/')  
    return redirect('index')         

def requests_view(request):
    if request.user.is_authenticated():
        user = request.user
        user_out = user
        user_type= USER_TYPE.SHOPPER
        requests = []
        if user.is_superuser:
            user_type = USER_TYPE.ADMIN
            requests = Request.all()
        else:
            try:
                user_out = ShopperUser.objects.get(user=user)
                requests = user_out.sentRequests.all()
                Request.expireRequests(requests);
            except ShopperUser.DoesNotExist:
                user_out = MerchantUser.objects.get(user=user)
                requests = user_out.receivedRequests.filter(status__in=[STATUS.PENDING_ANSWER, STATUS.ACCEPTED, STATUS.DELIVERY_PENDING, STATUS.DELIVERY_ON_REVIEW, STATUS.EXPIRED])
                # we need to expire at this time
                Request.expireRequests(requests);
                user_type = USER_TYPE.MERCHANT

        request_out = []
        for req in requests:
            request_out.append((req,STATUS.choices[req.status]))
        return render(request, 'main/myRequests.html', {'user': user_out, "requests" : request_out, "STATUSES" : STATUS.choices.values(), "user_type": user_type,})
    return redirect('index')


def shopper_my_profile(request):
    if request.user.is_authenticated():
        user = request.user
        shopperUser = ShopperUser.objects.get(user=user)
        profile = shopperUser.getPendingProfile()
        if not profile:
            profile = shopperUser.getActiveProfile()
        return render(request, 'main/myProfile.html', {'user': shopperUser, "profile": profile, "locales": _get_profile_for_usr(profile)})
    return redirect('index')

def confirm_sign_up(request, user_id, confirmation_key):
    abstractUser = _getAbstractUser(user_id)
    confirmationCode = re.sub(CONFIRMATION_LINK_INVALID_CHARS, '', abstractUser.password.split(settings.PASSWORD_ENCRIPTION_ALGORITHM)[1])
    if confirmationCode== confirmation_key:
        abstractUser.confirmed = True
        abstractUser.save()
        return render(request, 'main/accountConfirmation.html', {'is_confirmed': True})
    return render(request, 'main/accountConfirmation.html', {'is_confirmed': False})

def image_action_delete(request):
    if request.user.is_authenticated():
        user = request.user
        usrObj = _getAbstractUser(user.id)
        if isinstance(usrObj, MerchantUser): 
            profileObj = usrObj.getPendingProfile()
        else:
            profileObj = usrObj.getPendingProfile()            
        images = request.POST.getlist('delete_image')
        if not profileObj:
            profileObj = usrObj.getActiveProfile()
        for image in images:
            # delete the imgage from both profiles
            imageptr = profileObj.images.filter(id=image)
            imageptr.delete()
            if usrObj.getPendingProfile():
                imageptr = usrObj.getPendingProfile().images.filter(id=image)
                imageptr.delete()
        #description = merchantUser.profile
        return redirect('my_profile')
    return redirect('index')

def _is_profile_change(request, merchantUser):
    ret = False
    for loc in merchantUser.getActiveProfile().loc_profiles.all():
        ret = ret or loc.loc_profile == request.POST['description-' + str(loc.lang)]
        
    return (ret or
            (request.POST['last_name'] != merchantUser.getActiveProfile().last_name) or
            (request.POST['first_name'] != merchantUser.getActiveProfile().first_name) or
            'datafile' in request.FILES)

def _save_provile(request, user):
    # read all the descriptions
    descriptions = {}
    for key in ACCEPTED_LOCALE.choices:
        if 'description-' + str(key) in request.POST and request.POST['description-' + str(key)]:
            descriptions[key] = request.POST['description-' + str(key)]
    # There has to be at least one localized profile
    if not descriptions:
        messages.add_message(request, messages.ERROR, 'You need to provide at least one localized description')
        return
    profileObj = user.getPendingProfile()
        
    if user.getActiveProfile() and not _is_profile_change(request, user):
        if "select_image" in request.POST:
            user.profile_image = request.POST["select_image"]
        user.save()
        return redirect('my_profile')
    #if there is a profile on review then we update that profile
    if profileObj:
        if "select_image" in request.POST:
            user.profile_image = request.POST["select_image"]
            user.save()
    elif (user.getActiveProfile()):
        #merchantProfile = MerchantProfile()
        activeProfile = user.getActiveProfile()
        # For avoiding reduplicate the images in S3 we need to clone the rows for the new profile manually, we have to do it Manually becaue
        # if we save an Image Object then e need to load the image again in S3 when we only want to duplicate the DB row
        if isinstance(user, MerchantUser): 
            pk = MerchantProfile.objects.order_by('-pk')[0].pk + 1
            id = MerchantProfile.objects.order_by('-pk')[0].id + 1
        else:
            pk = ShopperProfile.objects.order_by('-pk')[0].pk + 1
            id = ShopperProfile.objects.order_by('-pk')[0].id + 1
        if activeProfile.images.all():
            imageTableName= activeProfile.images.all()[0]._meta.db_table
            profileImages = activeProfile.images.all()
        
            activeProfile.pk = pk
            activeProfile.id = id
            activeProfile.status=STATUS.ON_REVIEW
            activeProfile.save()
            cursor = connection.cursor()
            for img in profileImages:
                cursor.execute("insert into %s (profile_id, image, thumbnail) VALUES(%s, '%s','%s' )" % (imageTableName, activeProfile.pk, img.image.name, img.thumbnail.name))
        else:         
            activeProfile.pk = pk
            activeProfile.id = id
            activeProfile.status=STATUS.ON_REVIEW
            activeProfile.save()
        profileObj = user.getPendingProfile()
    else:
        if isinstance(user, MerchantUser): 
            profileObj = MerchantProfile()
        else:
            profileObj = ShopperProfile()
        user.profiles.add(profileObj)
        profileObj.save()
    #merchantUser.profiles.add(merchantProfile)
    #merchantProfile = MerchantProfile()
    profileObj.first_name = request.POST.get("first_name", "")
    profileObj.last_name = request.POST.get("last_name", "")
    for key in descriptions:
        try:
            loc_profile = profileObj.loc_profiles.get(lang = key)
            loc_profile.loc_profile = descriptions[key]
            loc_profile.save()
        except LocalizedModel.DoesNotExist:
            profileObj.loc_profiles.create(loc_profile=descriptions[key], lang=key)
    
    if 'datafile' in request.FILES:
        if len(profileObj.images.all()) == settings.MAX_ALLOWED_PICS_MERCHANT:
            messages.add_message(request, messages.WARNING, 'maximum allowed pics (%s) reached' % settings.MAX_ALLOWED_PICS_MERCHANT)
            return redirect('my_profile')
        profileObj.images.create(image=request.FILES['datafile'])
    if 'select_image' in request.POST:
        profileObj.profile_image = request.POST['select_image']
    profileObj.save()
    messages.add_message(request, messages.INFO, 'Profile updated, please wait for profile approval')
    
def save_merchant_profile(request):
    user = request.user
    merchantUser = MerchantUser.objects.get(user=user)
    _save_provile(request, merchantUser)
    return redirect('my_profile')

def save_shopper_profile(request):
    user = request.user
    shopperUser = ShopperUser.objects.get(user=user)
    _save_provile(request, shopperUser)
    return redirect('my_profile')

def _shopper_create(username, password, email, lang=ACCEPTED_LOCALE.EN):
    return ShopperUser.objects.create_shopper_user(username=username, email=email, password=password, lang=lang)

def shopper_sign_up_api(request):
    try:
        shopper = _shopper_create(request.POST['username'], request.POST['password'], request.POST['email'])
        _send_confirmation_mail(request.build_absolute_uri(), 'WelcomeToCashGShopper', 'no-reply-customers-shoppers@cashg.com', shopper)
    except Exception:
        pass 
    return HttpResponse('{"status": "OK"}')

def shopperSignUp(request):
    try:
        shopper = _shopper_create(request.POST['username'], request.POST['password'], request.POST['email'], ACCEPTED_LOCALE.get_constant(request.session['django_language'].upper()))
        _send_confirmation_mail(request.build_absolute_uri(), 'WelcomeToCashGShopper', 'no-reply-customers-shoppers@cashg.com', shopper)
    except Exception:
        pass
    return HttpResponse("an email was sent to " + request.POST['email'] + "please confirm it for complete the registration")

@csrf_exempt
def merchant_sign_up_api(request):
    req = eval(request.raw_post_data)
    _merchant_create(req['username'], req['password'], req['email'], req['age'])
    return HttpResponse('{"status": "OK"}')

def _merchant_create(username, password, email, age, lang):
    return MerchantUser.objects.create_merchant_user(username=username, email=email, password=password, age=age, lang=lang)

def login_api(request):
    username = request.GET["username"]
    password = request.GET["password"]
    user = authenticate(username=username, password=password)
    if user is not None:
        login(request, user)
        return HttpResponse('{"status": "OK", "session_key": "%s"}' %(request.session._session_key))
    return HttpResponse('{"status": "NG", "message": "user not logged"}')

def logout_api(request):
    if '_auth_user_id' in request.session:
        logout(request)
        return HttpResponse('{"status": "OK", "message": "user logged out"}')
    return HttpResponse('{"status": "NG", "message": "user already logged out"}')

def signUp(request):
    merchant = _merchant_create(request.POST['username'], request.POST['password'], request.POST['email'], request.POST['age'], ACCEPTED_LOCALE.get_constant((request.session.get('django_language', translation.get_language()).upper())))       
    _send_confirmation_mail(request.build_absolute_uri(), 'WelcomeToCashGMerchant', 'no-reply-customers-merchants@cashg.com', merchant)
    return HttpResponse("an email was sent to " + request.POST['email'] + "please confirm it for complete the registration")

def _send_confirmation_mail(base_confirmation_url, template, from_email, user):
    
    confirmationCode = re.sub(CONFIRMATION_LINK_INVALID_CHARS, '', user.password.split(settings.PASSWORD_ENCRIPTION_ALGORITHM)[1])
    confLink =  "%s%s/%s/%s/" %(base_confirmation_url, "confirm", user.id, confirmationCode)
    cashGUtil.sendMail(template, user.username, from_email, user.email, {'name': 'confirmation_link', 'content': confLink})
    #mapi = MailSnake(settings.MANDRILL_API_KEY, api='mandrill')
    #mapi.messages.send_template(track_opens=True,
    #              template_name= template,
    #              template_content=[{'name':'username', "content": user.username}],

    #              message={
    #              'subject':'Welcome to CashG %s' %(user.username),
    #              'from_email':from_email,
    #              'from_name':'Welcome to CashG',
    #              'to':[{'email':user.email, 'name': user.username}],
    #              'global_merge_vars': [{'name': 'confirmation_link', 'content': confLink}]}
    #              )


